#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 文件名：tcpclient.py
import codecs
import subprocess
import locale
import socket
import time

# 测试数据常量
BIND_WIDTH = 40
PACKAGE_SIZE = 10


def getstdout(p):
    mylist = []
    while True:
        data = p.stdout.readline()
        if data == b'':
            if p.poll() is not None:
                break
        else:
            mylist.append(data.decode(codecs.lookup(locale.getpreferredencoding()).name))
    return mylist


START_FLAG = 0
MaxBytes = 1024 * 1024
host = '10.112.149.27'
port = 2333
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.settimeout(30)
client.connect((host, port))
inputData = input()  # 等待输入数据
while True:
    if inputData == "quit":
        print("我要退出了，再见")
        break
    sendBytes = client.send(inputData.encode())
    if sendBytes <= 0:
        break
    try:
        recvData = client.recv(MaxBytes)
        print(recvData.decode())
        if START_FLAG == 1:
            START_FLAG = 0  # 测量完成，将标志位置为0，等待击发状态
        if recvData.decode() == "start test":
            time.sleep(1)
            print("开始测试，测试带宽为：" + str(BIND_WIDTH) + "MB/s，测量数据的大小为" + str(PACKAGE_SIZE) + "MB，（单位均为字节）")
            ps = subprocess.Popen(
                '.\iperf3.exe -c 10.112.149.27 -u -b ' + str(BIND_WIDTH) + 'M -n ' + str(PACKAGE_SIZE) + 'M',
                stdin=subprocess.PIPE,
                stdout=subprocess.PIPE,
                shell=True)
            resultlist = getstdout(ps)
            l = len(resultlist)
            print(resultlist[l - 4])
            speed = str(resultlist[l - 4]).split("  ")[5]
            lost_rate = str(resultlist[l - 4]).split("  ")[7]
            print("第一台主机当前测试平均速度："+speed+"；"+"当前测试平均丢包率："+lost_rate+"；")
            print("本次测量结束...等待下一次测量...")
            client.send("send finished".encode())  # 通知Server此时已经发送完成
        if not recvData:
            print('wdnmd接收数据为空，我要退出了')
            break
        localTime = time.asctime(time.localtime(time.time()))
        print(localTime, ' 接收到数据字节数:', len(recvData))
    except:
        print("try again now....")
        sendBytes = client.send(b"Test begin")
        time.sleep(2)

client.close()
print("我已经退出了，后会无期")
